<template>
  <div id="app">
    <el-card shadow="always">
      <!--      条件查询-->
      {{workersearch}}
      <el-form :inline="true" :model="workersearch" class="demo-form-inline">
        <el-form-item >
          <el-input v-model="workersearch.name" placeholder="姓名"></el-input>
        </el-form-item>
        <el-form-item >
          <el-input v-model="workersearch.age" placeholder="年龄"></el-input>
        </el-form-item>
        <el-form-item >
          <el-select v-model="workersearch.did" placeholder="部门">
            <el-option label="所有部门" value="0"></el-option>
            <el-option :label="d.did" :value="d.did" v-for="d in departmentList " :key="d.did"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="plain"  @click="search">查询</el-button>
          <el-button type="success"  @click="add">添加</el-button>
          <el-button type="danger" @click="handleDelete">批量删除</el-button>
        </el-form-item>
      </el-form>
      <!--      查询学生列表-->
      <el-table
          :data="workerList"
          style="width: 100%"
          @selection-change="handleSelectionChange">
        <el-table-column
            type="selection"
        >
        </el-table-column>
        <el-table-column
            label="id"
            align="center"
            prop="id">
        </el-table-column>
        <el-table-column
            label="姓名"
            align="center"
            prop="name">
        </el-table-column>
        <el-table-column
            label="年龄"
            align="center"
            prop="age">
        </el-table-column>
        <el-table-column
            label="部门"
            align="center"
            prop="did">
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
                size="mini"
                @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </el-card>
    <el-dialog :title="title" :close-on-click-modal="false" :visible.sync="dialogFormVisible">
      {{worker}}
      <el-form :model="worker" :rules="rules" ref="ruleForm">
        <el-form-item label="员工姓名"  prop="name" :label-width="formLabelWidth">
          <el-input v-model="worker.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="员工年龄" prop="age" :label-width="formLabelWidth">
          <el-input v-model.number="worker.age" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="部门" prop="did" :label-width="formLabelWidth">
          <el-select v-model="worker.did" placeholder="请选择所在部门">
            <el-option label="所有部门" value="0"></el-option>
            <el-option :label="d.did" :value="d.did" v-for="d in departmentList" :key="d.did"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveworker">保存</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import workerapi from "@/api/worker"
import departmentapi from "@/api/department"



export default {
  data(){
    // 自定义校验规则
    let checkAge = (rule, value, callback) => {
      if (value === '' || value == null) {
        return callback(new Error('年龄不能为空'))
      } else if (!Number.isInteger(value)) {
        return callback(new Error('年龄必须为数字值'))
      } else if (value < 1 || value > 200) {
        return callback(new Error('年龄必须在1-200之间'))
      } else {
        callback()
      }
    }

    return {
      workerList: [],
      departmentList: [],//所有部门
      workersearch: {},
      worker: {},
      page: 1,
      pageSize: 5,
      total: 100,
      title:'添加员工',
      formLabelWidth: '100px',
      dialogFormVisible: false,
      ids:[],
      multipleSelection:[],//数组，选中多项

      rules: {
        // id: [
        //   { required: true, message: '请输入学生id', trigger: 'blur' },
        // ],
        name: [
          {required: true, message: '请输入学生姓名', trigger: 'blur'},
        ],
        age: [
          // { required: true, message: '请输入学生年龄', trigger: 'blur' },
          {validator : checkAge, trigger:'blur'}
        ],
        did: [
          {required: true, message: '请选择部门', trigger: 'blur'},
        ]

      }
    }

  },

  created() {
    // this.findworker()
    // this.findByPage()
    this.finddepartment()
    this.search()
  },


  methods: {



    async findworker() {
      const {data:res}= await workerapi.findworker()
      console.log(res)
      if(res.code === 200){
        this.workerList=res.data.list
      }
    },

    async finddepartment(){
      const {data:res} =await departmentapi.finddepartment()
      console.log(res)
      if(res.code === 200){
        this.departmentList=res.data.list;
      }
    },

    async search(){
      const {data:res} = await workerapi.search(this.page,this.pageSize,this.workersearch)
      console.log(res)
      if (res.code === 200) {
        this.workerList = res.data.wo.rows
        this.total = res.data.wo.total
      }

    },

    async findByPage(){
      const {data:res} = await workerapi.findByPage(this.page,this.pageSize)
      console.log(res)
      if(res.code === 200){
        this.workerList=res.data.wo.rows
        this.total=res.data.wo.total
      }
    },

    add(){
      this.title='添加员工'
      this.worker={}
      this.dialogFormVisible = true
    },

    saveworker(){
      this.$refs.ruleForm.validate(async valid=>{
        let url = "/worker/add"
        let method="post"
        if(this.worker.id){
          url = "/worker/update"
          method="put"
        }
        if(valid){
          const{data:res}=await workerapi.save(url,method,this.worker)
          console.log("res:",res)
          if (res.code === 200) {
            this.$message({
              type:'success',
              message:res.message,
              onClose:() =>{
                this.dialogFormVisible=false
                this.search()
              }
            })
          }else{
            this.$message({
              type:'error',
              message:res.message
            })
          }
        }else {
          console.log("验证失败")
        }
      })

    },

    handleDelete(index,row){
      this.ids=[];
      if(row){
        this.ids.push(row.id)
      }else {
        this.ids = this.multipleSelection.map(m => m.id)
      }
      this.$confirm(`是否真的要删除学号为${this.ids}的学生吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let _this=this
        workerapi.deleteworker(this.ids)
            .then(({data:res})=>{
              console.log("res:",res)
              if (res.code === 200) {
                this.$message({
                  type: 'success',
                  message: res.message,
                  onClose: () => {
                    // 重新加载数据
                    _this.search()
                  }
                })
              } else {
                this.$message({
                  type: 'error',
                  message: res.message
                })
              }
            })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },




    handleEdit(index,row){
      this.title='修改员工信息'
      this.worker=row
      this.dialogFormVisible=true

      console.log(index,row)
    },

    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log(this.multipleSelection)
    },


    handleSizeChange(val) {
      this.pageSize=val
      // this.findByPage()
      this.search()
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.page=val
      // this.findByPage()
      this.search()
      console.log(`当前页: ${val}`);
    }

  }





}

</script>

<style>
.el-card{
  width: 90%;
}
#app{
  display: flex;
  justify-content: center;
}
.el-pagination{
  margin-top: 20px;
  text-align: right;
}
</style>
